package com.nowcoder.controller;

import com.nowcoder.entity.*;
import com.nowcoder.event.EventProducer;
import com.nowcoder.service.CommentService;
import com.nowcoder.service.DiscussPostService;
import com.nowcoder.service.LikeService;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.CommunityConstant;
import com.nowcoder.utils.CommunityUtil;
import com.nowcoder.utils.HostHolder;
import com.nowcoder.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RequestMapping("/discuss")
@Controller
public class DiscussPostController implements CommunityConstant {
    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Autowired
    CommentService commentService;

    @Autowired
    LikeService likeService;

    @Autowired
    EventProducer eventProducer;


    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        System.out.println("addDiscussPost" + title);
        User user = HostHolder.getUser();
        if(user == null) {
            return CommunityUtil.getJSONString(403, "你还没有登陆");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);
        System.out.println(post);

        // 触发发帖事件
        Event event = new Event()
            .setTopic(TOPIC_PUBLISH)
            .setUserId(user.getId())
            .setEntityType(ENTITY_TYPE_POST)
            .setEntityId(post.getId());
        eventProducer.fireEvent(event);

        // 计算帖子分数，加入到Redis中
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, post.getId());

        return CommunityUtil.getJSONString(0, "发布成功");
    }

    @GetMapping("/detail/{postId}")
    public String getDiscussPost(@PathVariable("postId") int postId, Model model, Page page) {
        // 查询帖子
        DiscussPost post = discussPostService.selectDiscussPostById(postId);
        // 查询作者
        User user= userService.findUserById(post.getUserId());
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId);
        model.addAttribute("likeCount", likeCount);
        // 点赞状态
        int likeStatus = HostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(HostHolder.getUser().getId(), ENTITY_TYPE_POST, postId);
        model.addAttribute("likeStatus", likeStatus);

        // 添加到模型中
        model.addAttribute("post", post);
        model.addAttribute("user", user);

        // 评论分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + postId);
        page.setRows(post.getCommentCount());

        // 评论列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        List<Comment> commentsList = commentService.findCommentsByEntity(ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());

        // 生成评论VO
        for(Comment comment: commentsList) {
            // 评论和对应作者
            Map<String, Object> commentVo = new HashMap<>();
            commentVo.put("comment", comment);
            commentVo.put("user", userService.findUserById(comment.getUserId()));
            // 点赞数量
            likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
            commentVo.put("likeCount", likeCount);
            // 点赞状态
            likeStatus = HostHolder.getUser() == null ? 0 :
                    likeService.findEntityLikeStatus(HostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
            commentVo.put("likeStatus", likeStatus);

            // 回复列表
            List<Map<String, Object>> replyVoList = new ArrayList<>();
            List<Comment> replyList = commentService.findCommentsByEntity(ENTITY_TYPE_COMMENT, comment.getId(),
                    0, Integer.MAX_VALUE);
            for(Comment reply: replyList) {
                Map<String, Object> replyVo = new HashMap<>();
                replyVo.put("reply", reply);
                replyVo.put("user", userService.findUserById(reply.getUserId()));

                // 点赞数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 点赞状态
                likeStatus = HostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(HostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复目标
                User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                replyVo.put("target", target);
                replyVoList.add(replyVo);
            }
            commentVo.put("replys", replyVoList);
            int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
            commentVo.put("replyCount", replyCount);

            // 最后添加进去
            commentVoList.add(commentVo);
        }

        model.addAttribute("comments", commentVoList);


        return "/site/discuss-detail";
    }
}




















